import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

public class JSONExample2 extends HttpServlet{
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		
		String json = readJSONStringFromRequestBody(request);
		JSONObject jsonObject = null;
		try{
			jsonObject = new JSONObject(json);
		}catch(JSONException e){
			System.out.println("JSONException");
			e.printStackTrace();
		}
		String car = "";
		String color = "";
		try {
			car = jsonObject.getString("make");
			color = jsonObject.getString("color");
		} catch (JSONException e1) {
			System.out.println("JSONException");
			e1.printStackTrace();
		}
		String fCar = "Aodi";
	
		if("AUDIO".equalsIgnoreCase(car)){
			fCar = "Aodi";
		}else if("BENZ".equalsIgnoreCase(car)){
			fCar = "Benchi";
		}else if("BMW".equalsIgnoreCase(car)){
			fCar = "Baoma";
		}else if("TOYOTA".equalsIgnoreCase(car)){
			fCar = "Fengtian";
		}

		response.setContentType("text/xml;charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		StringBuffer responseText = new StringBuffer();
		responseText.append("<?xml version=\"1.0\"?>");
		responseText.append("<car><make>")
		.append(fCar).append("</make>").append("<color>")
		.append(color).append("</color></car>");

		response.getWriter().print(responseText);
	}

	private String readJSONStringFromRequestBody(HttpServletRequest request) {
		StringBuffer json = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
			while((line = reader.readLine()) != null){
				json.append(line);
			}
		} catch (IOException e) {
			System.out.println("IOException");
			e.printStackTrace();
		}
		return json.toString();
	}

	
}
